#!/usr/bin/env python
'''
    searches for words and phrases in files indexed by docindex.

SYNOPSIS
    Execute script with --help option to view synopsis.

HOME PAGE
    http://www.methods.co.nz/docindexer/

COPYING
    Copyright (C) 2007 Stuart Rackham. Free use of this software is
    granted under the terms of the MIT License.
'''
__author__ = 'Stuart Rackham <srackham@methods.co.nz>'
# The following line is set automatically from main.aap
__version__ = '0.9.4.3'

import os, sys, string
from docindexer.common import EDocIndexer, decode_input, safe_print
from docindexer.docsearcher import DocSearcher

def main():
    __pychecker__ = 'no-shadowbuiltin'
    def args_error(msg):
        print options.get_usage()
        safe_print('%s: error: %s' % (os.path.basename(sys.argv[0]),msg))
        sys.exit(1)
    # Process command line options.
    import optparse
    usage = 'usage: %prog [options] lucene_query [searchdir]'
    version = '%%prog %s' % __version__
    options = optparse.OptionParser(usage=usage,version=version)
    options.add_option('-a', '--and',
        action='store_true',
        dest='and_op',
        help='join terms with AND operator')
    options.add_option('-F', '--format',
        action='store',
        type='string',
        dest='format',
        metavar='FORMAT',
        help='results list format')
    options.add_option('-l', '--list',
        action='store_true',
        dest='list',
        help='use long index listing format')
    options.add_option('-q', '--quiet',
        action='store_true',
        dest='quiet',
        help='suppress results list')
    options.add_option('-s', '--summary',
        action='store_true',
        dest='summary',
        help='print a summary of search results')
    (opts, args) = options.parse_args()
    if len(args) == 0:
        args_error('incorrect number of arguments')
    args = [decode_input(s.strip()) for s in args]
    if '' in args:
        args_error('zero length arguments are not allowed')
    # Do the work.
    if os.path.isdir(args[-1]):
        dir = args.pop()
        if len(args) == 0:
            args_error("missing query ('%s' is a directory)" % dir)
    else:
        dir = os.getcwd()
    searcher = DocSearcher(searchdir=dir)
    searcher.parse_query(' '.join(args), options.values.and_op)
    if options.values.format is not None:
        searcher.format = options.values.format
    elif options.values.list:
        searcher.format = '%(score)4.2f  ' + searcher.LISTING_FORMAT
    searcher.printf(not options.values.quiet, options.values.summary)

if __name__ == '__main__':
    __pychecker__ = 'no-badexcept'  # KeyboardInterrupt is OK.
    try:
        main()
    except EDocIndexer,e:
        print >>sys.stderr, 'failed: %s' % e
        sys.exit(1)
    except KeyboardInterrupt:
        print >>sys.stderr, 'user keyboard interrupt'
        sys.exit(1)

# vim: set ts=4 sw=4:
